<template lang="pug">
  #gmap
</template>

<script>
let geocoder, marker, address

export default {
  name: 'gdMapModal',
  data() {
    return {
      lnglatXY: []
    }
  },
  mounted() {
    var self = this
    const map = new AMap.Map('gmap', {
      resizeEnable: true,
      zoom: 16
    });
    // map.plugin('AMap.Geolocation', function() {
    //  var geolocation = new AMap.Geolocation({
    //    enableHighAccuracy: true, //是否使用高精度定位，默认:true
    //    timeout: 10000, //超过10秒后停止定位，默认：无穷大
    //    buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
    //    zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    //    buttonPosition: 'RB'
    //  });
    //  map.addControl(geolocation)
    //  geolocation.getCurrentPosition()
    //  AMap.event.addListener(geolocation, 'complete', onComplete) //返回定位信息
    //  AMap.event.addListener(geolocation, 'error', onError) //返回定位出错信息
    // })
    map.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Marker'], function() {
      map.addControl(new AMap.ToolBar())
      map.addControl(new AMap.Scale())
    })
    AMapUI.loadUI(['control/BasicControl'], function(BasicControl) {
      map.addControl(new BasicControl.LayerSwitcher({
        position: 'rb'
      }))
    })

    map.on('click', function(e) {
      // 先清除上个标记
      if(marker) {
        map.remove(marker)
      }
      self.regeocoder([e.lnglat.getLng(), e.lnglat.getLat()])
      marker = new AMap.Marker({
        position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
        offset: new AMap.Pixel(-10, -30),
        icon: '//webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 添加 Icon 图标 URL
        title: address
      })

      map.add(marker)
    })
    window.map = map
    self.regeocoder([116.39,39.9])
  },
  methods: {
    regeocoder(lnglatXY) { //逆地理编码
      var self = this
      map.plugin(['AMap.Geocoder'], function() {
        geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        })
        geocoder.getAddress(lnglatXY, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            self.geocoder_CallBack(result, lnglatXY)
          }
        })
      })
    },
    geocoder_CallBack(data, lnglatXY) {
      address = data.regeocode.formattedAddress //返回地址描述
      this.$emit('sendaddress', {address: address, lng: lnglatXY[0], lat: lnglatXY[1]})
    }
  }
}

</script>
<style lang="stylus">
#gmap
  margin: 0px
  height: 100%
  min-height 400px

.amap-logo
  display: none

.amap-copyright
  left: 0

.amap-geo
  display: none
</style>
